package com.lu.oss.tools;

import android.util.Base64;

import androidx.annotation.NonNull;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

/**
 * author: luqihua
 * date:2020/4/3
 * description: 数据转换工具类
 **/
public class DigestTools {
    private static final String TAG = "DigestTools";

    public static String getFileMd5Hex(@NonNull File file) {
        byte[] bytes = getFileMd5(file);
        if (bytes != null) {
            return byteToHex(bytes);
        } else {
            return null;
        }
    }

    public static String getFileMd5Base64(@NonNull File file) {
        byte[] bytes = getFileMd5(file);
        if (bytes != null) {
            return Base64.encodeToString(bytes, Base64.NO_WRAP);
        } else {
            return null;
        }
    }

    public static byte[] getFileMd5(File file) {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            MessageDigest digest = MessageDigest.getInstance("MD5");
            int len = fis.read(buffer);
            while (len > 0) {
                digest.update(buffer, 0, len);
                len = fis.read(buffer);
            }
            return digest.digest();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    /**
     * byte数组转hex
     *
     * @param bytes
     * @return
     */
    public static String byteToHex(byte[] bytes, int offset, int len) {
        String strHex;
        StringBuilder sb = new StringBuilder();
        int target = offset + len;
        if (target >= bytes.length) target = bytes.length;
        for (int i = offset; i < target; i++) {
            strHex = Integer.toHexString(bytes[i] & 0xFF);
            if (strHex.length() == 1) {
                sb.append("0");
            }
            sb.append(strHex); // 每个字节由两个字符表示，位数不够，高位补0
        }
        return sb.toString().trim().toUpperCase();
    }

    /**
     * byte数组转hex
     *
     * @param bytes
     * @return
     */
    public static String byteToHex(byte[] bytes) {
        return byteToHex(bytes, 0, bytes.length);
    }
}
